package com.www.applyword.fragment;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.classic.adapter.CommonRecyclerAdapter;
import com.google.android.material.tabs.TabLayout;
import com.www.applyword.Constants.Constants;
import com.www.applyword.R;
import com.www.applyword.adapter.HomeAdapter;
import com.www.applyword.adapter.HomeJobAdapter;
import com.www.applyword.adapter.HotJobAdapter;
import com.www.applyword.base.BaseFragment;
import com.www.applyword.bean.BannerBean;
import com.www.applyword.bean.HotJobBean;
import com.www.applyword.bean.JobListBean;
import com.www.applyword.bean.LoginBean;
import com.www.applyword.bean.OrderBean;
import com.www.applyword.event.EventConstants;
import com.www.applyword.event.MessageEvent;
import com.www.applyword.http.CallBack;
import com.www.applyword.http.HttpClient;
import com.www.applyword.ui.chat.ChoiceJobActivity;
import com.www.applyword.ui.home.HomeJobActivity;
import com.www.applyword.ui.home.HomeSignInActivity;
import com.www.applyword.ui.home.HotJobActivity;
import com.www.applyword.ui.home.HotJobDetailsActivity;
import com.www.applyword.ui.home.LocationActivity;
import com.www.applyword.ui.home.PostJobActivity;
import com.www.applyword.ui.home.SearchActivity;
import com.www.applyword.ui.home.WordPositionActivity;
import com.www.applyword.ui.my.MyJobTimeActivity;
import com.www.applyword.ui.my.MyRealNameActivity;
import com.www.applyword.utils.SPUtil;
import com.www.applyword.utils.Utils;
import com.www.applyword.view.MyImageLoader;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * @author Administrator
 */
public class HomeFragment extends BaseFragment {
    @BindView(R.id.linearLayout)
    LinearLayout linearLayout;
    @BindView(R.id.ll_fabu)
    LinearLayout llFabu;
    @BindView(R.id.ll_hot)
    LinearLayout llHot;
    @BindView(R.id.ll_new)
    LinearLayout llNew;
    @BindView(R.id.ll_location)
    LinearLayout llLocation;
    @BindView(R.id.ll_minqi)
    LinearLayout llMinqi;
    @BindView(R.id.ll_sign_in)
    LinearLayout ll_sign_in;
    @BindView(R.id.bannerContainer)
    Banner mBanner;
    @BindView(R.id.tv_location)
    TextView tv_location;
    @BindView(R.id.rl_home)
    RecyclerView rl_home;
    @BindView(R.id.rl_job)
    RecyclerView rlJob;
    @BindView(R.id.rl_job2)
    RecyclerView rlJob2;

    @BindView(R.id.tablayout)
    TabLayout tabLayout;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.tv_job)
    TextView tvJob;
    @BindView(R.id.tv_dic)
    TextView tvDic;
    @BindView(R.id.tv_comprehensive)
    TextView tvComprehensive;
    @BindView(R.id.rl_1)
    RelativeLayout rl1;


    private List<Fragment> fragments = new ArrayList<>();
    private List<String> tabs = new ArrayList<>();

    private List<String> list_path = new ArrayList<>();
    private HomeAdapter homeAdapter;
    private List<HotJobBean> hotJobBeans = new ArrayList<>();
    private int position;
    private int userInfo_state;
    private BannerBean.HotSearchBean hotSearch;
    private HotJobAdapter mHotJobAdapter;
    private String city;

    @Override
    protected int getLayoutResource() {
        return R.layout.home_fragment2;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initDate();
        setListener();
        rlJob.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (dy > 0) { // 当前处于上滑状态
                    rlJob.scrollToPosition(0);
                    Intent intent = new Intent(getActivity(), WordPositionActivity.class);
                    intent.putExtra("position", 0);
                    intent.putExtra("city", city);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.push_top_in,
                            R.anim.push_top_out);
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent messageEvent) {
        if (messageEvent.getMessageKey() != null) {
            if (messageEvent.getMessageKey().equals(EventConstants.REAL_NAME)) {
                getUserInfo();
            }
        }
    }


    private void initDate() {
        if (TextUtils.isEmpty(SPUtil.getString("city"))) {
            tv_location.setText("武汉市");
        } else {
            tv_location.setText(SPUtil.getString("city"));
        }

        list_path.clear();
        //  list_path.add("https://gss0.baidu.com/94o3dSag_xI4khGko9WTAnF6hhy/zhidao/wh%3D600%2C800/sign=e9873bfca944ad342eea8f81e09220cc/a8ec8a13632762d08fa73daea8ec08fa513dc602.jpg");

        // list_path.add("https://gss0.baidu.com/94o3dSag_xI4khGko9WTAnF6hhy/zhidao/wh%3D600%2C800/sign=e9873bfca944ad342eea8f81e09220cc/a8ec8a13632762d08fa73daea8ec08fa513dc602.jpg");

        // list_path.add("https://gss0.baidu.com/94o3dSag_xI4khGko9WTAnF6hhy/zhidao/wh%3D600%2C800/sign=e9873bfca944ad342eea8f81e09220cc/a8ec8a13632762d08fa73daea8ec08fa513dc602.jpg");

        // list_path.add("https://gss0.baidu.com/94o3dSag_xI4khGko9WTAnF6hhy/zhidao/wh%3D600%2C800/sign=e9873bfca944ad342eea8f81e09220cc/a8ec8a13632762d08fa73daea8ec08fa513dc602.jpg");
        //设置样式，里面有很多种样式可以自己都看看效果
        mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        mBanner.setImageLoader(new MyImageLoader());
        //设置轮播的动画效果,里面有很多种特效,可以都看看效果。
        mBanner.setBannerAnimation(Transformer.Default);
        //  mBanner.setBannerTitles(list_title);
        //设置轮播间隔时间
        mBanner.setDelayTime(3000);
        //设置是否为自动轮播，默认是true
        mBanner.isAutoPlay(true);
        //设置指示器的位置，小点点，居中显示
        mBanner.setIndicatorGravity(BannerConfig.CENTER);

        Map<String, Object> params = new HashMap<>();
        HttpClient.get(getActivity(), Constants.INDEX, params, new CallBack<BannerBean>() {
            @Override
            public void onSuccess(BannerBean bannerBean) {
                hotSearch = bannerBean.getHotSearch();
                list_path.clear();
                for (BannerBean.BannerBean2 bannerBean2 : bannerBean.getBanner()) {
                    list_path.add(bannerBean2.getBanner_Url());
                }
                mBanner.setImages(list_path).start();
                mBanner.setOnBannerListener(position -> {
                    //   Utils.showToastSafe("暂无连接地址");
                });
            }
        });

        //LinearLayoutManager中定制了可扩展的布局排列接口，子类按照接口中的规范来实现就可以定制出不同排雷方式的布局了
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        //配置布局，默认为vertical（垂直布局），下边这句将布局改为水平布局
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rl_home.setLayoutManager(layoutManager);
        rl_home.setItemAnimator(new DefaultItemAnimator());
        homeAdapter = new HomeAdapter(getActivity());
        rl_home.setAdapter(homeAdapter);
        hotJobBeans.clear();
        for (int i = 0; i < 3; i++) {
            HotJobBean hotJobBean = new HotJobBean();
            hotJobBean.setTitle(i + "");
            hotJobBeans.add(hotJobBean);
        }
        homeAdapter.replaceAll(hotJobBeans, true);

        fragments.clear();
        tabs.clear();
        tabs.add("小时结");
        tabs.add("日结");
        tabs.add("月结");
        fragments.add(new OrderSettlementFragment4());
        fragments.add(new OrderSettlementFragment4());
        fragments.add(new OrderSettlementFragment4());

        //设置TabLayout的模式
        viewPager.setAdapter(new TabAdapter(getChildFragmentManager()));
        viewPager.setCurrentItem(0);
        //关联ViewPager和TabLayout
        tabLayout.setupWithViewPager(viewPager);
        viewPager.setOffscreenPageLimit(fragments.size());
        getUserInfo();


        rlJob.setLayoutManager(new LinearLayoutManager(getActivity()));
        rlJob.setItemAnimator(new DefaultItemAnimator());
        mHotJobAdapter = new HotJobAdapter(getActivity());
        rlJob.setAdapter(mHotJobAdapter);

        rlJob2.setLayoutManager(new LinearLayoutManager(getActivity()));
        rlJob2.setItemAnimator(new DefaultItemAnimator());
        HomeJobAdapter homeJobAdapter = new HomeJobAdapter(getActivity());
        rlJob2.setAdapter(homeJobAdapter);

        Map<String, Object> params2 = new HashMap<>();
        params2.put("partJobId", "603290");
        params2.put("appKey", "QTSHE_ANDROID_MJ_WATERMELON");
        params2.put("townId", "87");
        params2.put("version", "4.35.0");
        //小时
        params2.put("versionCode", "10106");
        //职位福利
        params2.put("channel", "4");
        params2.put("downloadSource", "4");
        params2.put("deviceId", "869468021274583~ffe56626c3a6a4a9");
        params2.put("timestamp", "1596014357935");
        params2.put("sign", "8ef914390a28d46c7b65c8b20d22b99c");

        HttpClient.post(getActivity(), Constants.GETORDERLIST2, params2, new CallBack<List<JobListBean>>() {
            @Override
            public void onSuccess(List<JobListBean> jobListBeans) {
                homeJobAdapter.replaceAll(jobListBeans, true);
            }
        });
        //得到职位
        //   getJobList();

        homeJobAdapter.setOnItemClickListener(new CommonRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView.ViewHolder viewHolder, View view, int i) {
                startActivity(new Intent(getActivity(), HomeJobActivity.class).putExtra("id", homeJobAdapter.getItem(i).getPartJobId())
                        .putExtra("jobListBeans", (JobListBean) homeJobAdapter.getItem(i)));
            }
        });
    }

    private void getJobList() {
        Map<String, Object> params = new HashMap<>();
        params.put("Page", 1 + "");
        params.put("Rows", 5 + "");
        params.put("PositionType", 99 + "");
        if (!TextUtils.isEmpty(city) && !city.contains("武汉")) {
            params.put("AddressCity", city);
        } else {
            params.put("AddressCity", "");
        }
        params.put("PositionID", "");
        params.put("FamousEnterprisesType", 99 + "");
        //小时
        params.put("SalaryType", 0 + "");
        //职位福利
        params.put("Welfare", "");

        HttpClient.get(getActivity(), Constants.GETORDERLIST, params, new CallBack<List<OrderBean>>() {
            @Override
            public void onSuccess(List<OrderBean> orderBeans) {
                //  mHotJobAdapter.replaceAll(orderBeans, true);
            }
        });

        mHotJobAdapter.setOnItemClickListener((viewHolder, view, i) -> startActivity(new Intent(getActivity(), HotJobDetailsActivity.class)
                .putExtra("OrderID", mHotJobAdapter.getItem(i).getOrder_ID())));
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {

        } else {
            int state = SPUtil.getInt("userInfo_state", 0);
            if (state != 2) {
                getUserInfo();
            }
        }
    }

    private void getUserInfo() {
        Map<String, Object> params = new HashMap<>();
        params.put("userId", SPUtil.getString(Constants.USERID));
        HttpClient.get(getActivity(), Constants.GETUSERINFO, params, new CallBack<LoginBean>() {
            @Override
            public void onSuccess(LoginBean result) {
                userInfo_state = result.getUser().getUserInfo_State();
                SPUtil.put("userInfo_state", userInfo_state);
            }
        });
    }

    private void setListener() {
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        position = 0;
                        Intent intent = new Intent(getActivity(), WordPositionActivity.class);
                        intent.putExtra("position", 0);
                        intent.putExtra("city", city);
                        startActivity(intent);
                        getActivity().overridePendingTransition(R.anim.push_top_in,
                                R.anim.push_top_out);
                        break;
                    case 1:
                        position = 1;
                        Intent intent2 = new Intent(getActivity(), WordPositionActivity.class);
                        intent2.putExtra("position", 1);
                        intent2.putExtra("city", city);
                        startActivity(intent2);

                        getActivity().overridePendingTransition(R.anim.push_top_in,
                                R.anim.push_top_out);
                        break;
                    case 2:
                        position = 2;
                        Intent intent3 = new Intent(getActivity(), WordPositionActivity.class);
                        intent3.putExtra("position", 2);
                        intent3.putExtra("city", city);
                        startActivity(intent3);
                        getActivity().overridePendingTransition(R.anim.push_top_in,
                                R.anim.push_top_out);
                        break;
                    default:
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }


    @OnClick({R.id.linearLayout, R.id.ll_fabu, R.id.ll_hot, R.id.ll_new, R.id.ll_location, R.id.ll_minqi, R.id.ll_sign_in
            , R.id.tv_city, R.id.tv_job, R.id.tv_dic, R.id.tv_comprehensive, R.id.ll_search,R.id.cv_online_visits, R.id.rl_1, R.id.rl_3})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //搜索
            case R.id.ll_search:
                startActivity(new Intent(getActivity(), SearchActivity.class).putExtra("hotSearch", hotSearch));
                break;
            case R.id.linearLayout:
                startActivityForResult(new Intent(getActivity(), LocationActivity.class), 100);
                break;
            case R.id.ll_fabu:
                if (userInfo_state == 0) {
                    Utils.showToastSafe("请先实名认证后发布招聘信息");
                    startActivity(new Intent(getActivity(), MyRealNameActivity.class));
                    return;
                }
                if (userInfo_state == -1) {
                    Utils.showToastSafe("您的实名认证正在审核中");
                    return;
                }

                startActivity(new Intent(getActivity(), PostJobActivity.class));
                break;
            case R.id.ll_hot:
                startActivity(new Intent(getActivity(), HotJobActivity.class).putExtra("type", 1));
                break;
            case R.id.ll_new:
                startActivity(new Intent(getActivity(), HotJobActivity.class).putExtra("type", 2));
                break;
            case R.id.ll_location:
                startActivity(new Intent(getActivity(), HotJobActivity.class).putExtra("type", 3));
                break;
            case R.id.ll_minqi:
                startActivity(new Intent(getActivity(), HotJobActivity.class).putExtra("type", 4));
                break;
            //签到
            case R.id.ll_sign_in:
                startActivity(new Intent(getActivity(), HomeSignInActivity.class).putExtra("userInfo_state", userInfo_state));
                break;

            case R.id.tv_city:
                Intent intent = new Intent(getActivity(), WordPositionActivity.class);
                intent.putExtra("position", position);
                intent.putExtra("city", city);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.push_top_in,
                        R.anim.push_top_out);
                break;
            case R.id.tv_job:
                Intent intent2 = new Intent(getActivity(), WordPositionActivity.class);
                intent2.putExtra("position", position);
                intent2.putExtra("city", city);
                startActivity(intent2);
                getActivity().overridePendingTransition(R.anim.push_top_in,
                        R.anim.push_top_out);
                break;
            case R.id.tv_dic:
                Intent intent3 = new Intent(getActivity(), WordPositionActivity.class);
                intent3.putExtra("position", position);
                intent3.putExtra("city", city);
                startActivity(intent3);
                getActivity().overridePendingTransition(R.anim.push_top_in,
                        R.anim.push_top_out);
                break;
            case R.id.tv_comprehensive:
                Intent intent4 = new Intent(getActivity(), WordPositionActivity.class);
                intent4.putExtra("position", position);
                intent4.putExtra("city", city);
                startActivity(intent4);
                getActivity().overridePendingTransition(R.anim.push_top_in,
                        R.anim.push_top_out);
                break;
            case R.id.cv_online_visits:
                startActivity(new Intent(getActivity(), ChoiceJobActivity.class).putExtra("classificationId","10139"));
                break;
            case R.id.rl_1:
                startActivity(new Intent(getActivity(), ChoiceJobActivity.class).putExtra("type", 8).putExtra("classificationId","10139"));
                break;
            case R.id.rl_3:
                startActivity(new Intent(getActivity(), ChoiceJobActivity.class).putExtra("type", 3).putExtra("classificationId","10139"));
                break;
            default:
        }
    }




    class TabAdapter extends FragmentPagerAdapter {
        public TabAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        //显示标签上的文字
        @Override
        public CharSequence getPageTitle(int position) {
            return tabs.get(position);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case -1:
                city = data.getStringExtra("city");
                tv_location.setText(city);
                tvCity.setText("全" + city);
                getJobList();
                break;
            default:
                break;
        }
    }
}
